package com.livegoods.service;

import com.livegoods.pojo.Item;
import com.livegoods.pojo.LivegoodsResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class HotProductServiceImpl implements HotProductService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Value("${livegoods.fastdfs.nginx}")
    private String nginx;

    @Override
    public LivegoodsResult findHotProdcutByCity(String city) {
        try{
            Query query = new Query(Criteria.where("city").is(city));
            query.with(PageRequest.of(0,4,Sort.by(Sort.Order.desc("sales"))));
            List<Item> items = mongoTemplate.find(query, Item.class);
            for (Item item : items) {
                item.setImg(nginx+item.getImg());
            }
            return  LivegoodsResult.ok(items);
        }catch (Exception e){
            return  LivegoodsResult.error("查询热销商品失败，请联系管理员..");
        }
    }
}
